package com.pai4j.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.rest.uris:http://localhost:9200}")
    private String uris;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost[] hosts = parseUris(uris);
        RestClientBuilder builder = RestClient.builder(hosts);
        return new RestHighLevelClient(builder);
    }

    private HttpHost[] parseUris(String urisStr) {
        if (urisStr == null || urisStr.isEmpty()) {
            return new HttpHost[]{new HttpHost("localhost", 9200, "http")};
        }
        String[] parts = urisStr.split(",");
        List<HttpHost> list = new ArrayList<>();
        for (String part : parts) {
            String trimmed = part.trim();
            if (trimmed.isEmpty()) continue;
            URI uri = URI.create(trimmed);
            String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
            int port = uri.getPort() == -1 ? ("https".equalsIgnoreCase(scheme) ? 443 : 9200) : uri.getPort();
            list.add(new HttpHost(uri.getHost(), port, scheme));
        }
        return list.toArray(new HttpHost[0]);
    }
}
